package com.xncoding.valid.Converter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xncoding.valid.dto.Users;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 请求入参数解析
 */
public class PackHttpMessageConverter implements HttpMessageConverter<Object> {

    // 设置自定义的Content-Type类型application/pack;charset=UTF-8，这样就限定了只有请求的内容类型是该类型才会使用该转换器进行处理
    private static final MediaType PACK = new MediaType("application", "pack", StandardCharsets.UTF_8) ;

    // 判断当前转换器是否能够读取数据
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return PACK.equals(mediaType) ;
    }
    // 判断当前转换器是否可以将结果数据进行输出到客户端
    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return true ;
    }
    // 返回当前转换器只支持application/pack类型的数据格式
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return Arrays.asList(PACK) ;
    }

    /**
     * 从从请求中读取数据读取 aa|bb|cc|dd  格式数据
     * application/pack;charset=UTF-8
      */
    @Override
    public Object read(Class<? extends Object> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        InputStream is = inputMessage.getBody() ;
        String res = IOUtils.toString(is, StandardCharsets.UTF_8) ;
        // 这里简单处理只针对Users类型的对象处理
        if (clazz == Users.class) {
            try {
                // 创建实例
                Users target = (Users) clazz.newInstance() ;
                String[] s = res.split("\\|");
                target.setId(s[0]) ;
                target.setName(s[1]) ;
                target.setAge(s[2]) ;
                target.setIdNo(s[3]) ;
                return target ;
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace() ;
            }
        }
        return null ;
    }

    // 将Controller方法返回值写到客户端
    @Override
    public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        // 设置响应头为json格式
        outputMessage.getHeaders().add("Content-Type", "application/json;charset=UTF-8") ;
        ObjectMapper mapper = new ObjectMapper() ;
        OutputStream os = outputMessage.getBody();
        // 输出结果内容
        os.write(mapper.writeValueAsString(t).getBytes(StandardCharsets.UTF_8)) ;
        os.flush();
    }

}